<template>
  <div class="addMember">
    <van-nav-bar
      :title="title"
      left-arrow
      @click-left="goBackHandle"
      :fixed="true"
      :border="false"
      :safe-area-inset-top="true"
      style="padding-top: 0px"
    >
    </van-nav-bar>
    <div class="dataContent">
      <div>
        <div class="contentTop"></div>
        <van-form ref="memberInfo">
          <van-field
            v-model="memberInfo.username"
            autocomplete="off"
            name="姓名"
            label="姓名"
            placeholder="请输入姓名"
            :rules="[{ required: true }]"
            clearable
          />
          <van-field
            v-model="memberInfo.mobile"
            type="number"
            name="手机号"
            label="手机号"
            placeholder="请输入手机号"
            autocomplete="off"
            :rules="[
              { required: true },
              { pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误！' }
            ]"
            clearable
          />
          <van-field
            v-model="memberInfo.email"
            autocomplete="off"
            name="邮箱"
            label="邮箱"
            placeholder="请输入邮箱"
            clearable
            :rules="[
              { required: true },
              {
                pattern:
                  /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
                message: '邮箱格式错误！'
              }
            ]"
          />
          <van-field
            v-model="memberInfo.vendor"
            autocomplete="off"
            name="厂商信息"
            label="厂商信息"
            placeholder="请输入厂商信息"
            clearable
          />
          <div class="contentTop"></div>
          <van-field
            readonly
            clickable
            name="部门"
            :value="deptName"
            label="部门"
            placeholder="请选择部门"
            :rules="[]"
            @click="disabled ? (showPicker = false) : (showPicker = true)"
            :disabled="disabled"
            ><template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <!-- <van-field
            v-model="memberInfo.position"
            autocomplete="off"
            name="职务"
            label="职务"
            placeholder="请输入职务"
            :rules="[{ required: true }]"
            clearable
          /> -->
          <!-- 如果是管理员显示部门负责人 -->
          <van-field
            v-if="role == 2"
            readonly
            name="部门负责人"
            label="部门负责人"
            :rules="[{ required: true }]"
          >
            <template #input>
              <van-switch
                v-model="checked"
                disabled
                size="16"
                inactive-color="#f5f5f5"
              />
            </template>
          </van-field>
          <div class="contentTop"></div>
          <van-field
            readonly
            name="work_start"
            :value="memberInfo.work_start"
            label="上班时间"
            placeholder="请选择上班时间"
            @click="clickShowPicker(1)"
            :rules="[{ required: true }]"
          >
            <template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <van-field
            readonly
            name="work_end"
            :value="memberInfo.work_end"
            label="下班时间"
            placeholder="请选择下班时间"
            @click="clickShowPicker(2)"
            :rules="[{ required: true }]"
          >
            <template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <van-popup v-model="showPickerTime" position="bottom">
            <van-datetime-picker
              v-model="currentTime"
              type="time"
              title="选择时间"
              @confirm="onConfirmTime"
              @cancel="showPickerTime = false"
            />
          </van-popup>
          <van-popup v-model="showPicker" position="bottom">
            <van-picker
              show-toolbar
              :columns="columns"
              value-key="DeptName"
              @confirm="onConfirm"
              @cancel="showPicker = false"
            />
          </van-popup>
          <div class="footer" v-if="this.routerParam.ifNewMember">
            <van-button type="default" @click="submit(1)">保存</van-button>
            <van-button type="default" @click="submit(2)"
              >保存并继续添加</van-button
            >
          </div>
          <div class="footer" v-else>
            <van-button type="default" @click="submit(3)">保存</van-button>
            <van-button type="default" @click="submit(4)">删除</van-button>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>
<script>
import { SuccesFN } from '@/DceMessage'
import backMixin from '@/backMixin'
export default {
  name: 'addMember',
  mixins: [backMixin],
  data() {
    return {
      currentTime: '', //当前时间
      showPickerTime: false, //默认不显示时间选择器
      timeIndex: '',
      title: '添加成员',
      memberInfo: {
        username: '', //姓名
        mobile: '', //手机号
        email: '', //邮箱
        vendor: '', //厂商信息
        deptId: '', //部门
        // position: '', //职务
        work_start: '', //上班时间
        work_end: '' //下班时间
      },
      checked: false, //部门负责人
      deptName: '', //表单回显的部门
      columns: [], //部门选项
      showPicker: false, //是否展示Picker选择器
      role: '', //当前登录的用户权限
      paramsInfo: {}, //从路由带过来的对象
      disabled: false, //是否禁用
      checkedRole: '', //直属领导id
      roleForm: '', //部门负责人权限
      id: '', //当前登录用户id
      deptHead: '', //部门负责人
      // disabledDeptHead: false, //控制表单部门负责人是否禁用
      deptHeadName: '', //从部门接口过滤出来的部门门负责人
      leaderId: '', //提交参数部门负责人id
      routerParam: {}
    }
  },
  created() {
    this.routerParam = this.$route.params
    console.log(this.routerParam)
    // 获取部门信息
    this.getManagement()
    if (this.routerParam.ifNewMember) {
      this.title = '添加成员'
    } else {
      this.title = '编辑成员'
    }
    if (this.title == '编辑成员') {
      this.disabled = true
    }
    // 从缓存中获取权限
    this.role = JSON.parse(
      window.localStorage.getItem('attendance-records')
    ).role
    this.id = JSON.parse(window.localStorage.getItem('attendance-records')).id
  },
  mounted() {},
  methods: {
    // 点击时间选择器的确认按钮
    onConfirmTime() {
      if (this.timeIndex == 1) {
        this.memberInfo.work_start = this.currentTime
      } else if (this.timeIndex == 2) {
        this.memberInfo.work_end = this.currentTime
      }
      this.showPickerTime = false
    },
    // 点击上班时间或下班时间的表单
    clickShowPicker(val) {
      this.showPickerTime = true
      if (val == 1) {
        this.currentTime = this.memberInfo.work_start
      } else if (val == 2) {
        this.currentTime = this.memberInfo.work_end
      }

      this.timeIndex = val
    },
    // 获取部门信息
    getManagement() {
      this.$axios({
        url: '/attendance-api/department-query-list',
        method: 'get',
        params: {
          pageSize: this.pageSize,
          page: 1
        }
      }).then(res => {
        console.log(res)
        let temp = res.data.Object.List
        let tempDept = window.localStorage.getItem('attendance-records')
        let tempDeptId = JSON.parse(tempDept).deptId
        // 如果部门是-1 那么就是全部
        if (tempDeptId == '1615586587184205824') {
          this.columns = temp.filter(item => {
            return item.DeptId != tempDeptId
          })
        } else {
          this.columns = temp.filter(item => {
            return item.DeptId == tempDeptId
          })
        }
        console.log(this.columns)
        // 如果是编辑成员
        if (!this.routerParam.ifNewMember) {
          this.paramsInfo = this.routerParam.memberInfo
          console.log(this.paramsInfo)
          let deptHead = this.columns.filter(
            item => item.DeptId == this.paramsInfo.DeptId
          )[0].DeptHead
          let deptHeadId = this.columns.filter(
            item => item.DeptId == this.paramsInfo.DeptId
          )[0].DeptHeadId
          // 如果部门负责人LeaderId等于该员工的id
          //  if (
          //   this.paramsInfo.LeaderId == this.paramsInfo.Id ||
          //   deptHead == this.paramsInfo.Name
          // )
          if (this.paramsInfo.LeaderId == this.paramsInfo.Id) {
            // switch开关为开
            this.roleForm = 1
            this.checked = true
          } else {
            this.roleForm = 0
            this.checked = false
          }
          if (!this.checked) {
            this.leaderId = deptHeadId
            console.log(this.leaderId)
          } else {
            console.log(this.paramsInfo)
            this.leaderId = this.paramsInfo.Id
            console.log(this.leaderId)
          }
          console.log(this.paramsInfo)
          // 表单项的数据回显
          this.memberInfo = {
            username: this.paramsInfo.Name, //姓名
            mobile: this.paramsInfo.Mobile, //手机号
            email: this.paramsInfo.Email, //邮箱
            vendor: this.paramsInfo.Vendor, //厂商信息
            deptId: this.paramsInfo.DeptId, //部门
            work_start: this.paramsInfo.WorkStart, //上班时间
            work_end: this.paramsInfo.WorkEnd //下班时间
          }
          this.deptName = this.columns.filter(
            item => item.DeptId == this.paramsInfo.DeptId
          )[0].DeptName
        } else if (this.routerParam.ifNewMember) {
          // 如果是从成员列表页点击的添加成员，部门禁用并回显部门名称
          if (this.routerParam.deptId) {
            console.log('如果是成员列表点击的添加成员')
            this.disabled = true
            // 表单项选中的部门id是路由传过来的
            this.memberInfo.deptId = this.routerParam.deptId
            // 根据部门id得到部门名称
            this.deptName = this.columns.filter(
              item => item.DeptId == this.routerParam.deptId
            )[0].DeptName
            // 从部门接口数据中过滤出当前部门负责人
            this.deptHeadName = this.columns.filter(
              item => item.DeptId == this.routerParam.deptId
            )[0].DeptHead
            // 如果该部门已经有部门负责人
            if (this.deptHeadName) {
              // switch开关 默认关
              this.roleForm = 0
              this.checked = false
            } else {
              this.roleForm = 1
              this.checked = true
            }
            if (!this.checked) {
              this.leaderId = this.columns.filter(
                item => item.DeptId == this.routerParam.deptId
              )[0].DeptHeadId
            } else {
              // 应该等于该员工id，但是该员工还未添加成功没有id
              this.leaderId = ''
            }
          } else {
            // 如果是在成员管理页面点击的添加成员
            // 从部门接口的数据中根据当前选中的部门过滤出当前部门是否已有部门负责人
            this.getLeaderId()
            if (this.memberInfo.deptId) {
              console.log(this.checked)
              if (!this.checked) {
                this.leaderId = this.columns.filter(
                  item => item.DeptId == this.memberInfo.deptId
                )[0].DeptHeadId
                console.log(this.leaderId)
              } else {
                // 应该等于该员工id，但是该员工还未添加成功没有id
                this.leaderId = ''
              }
            }
          }
        }
      })
    },
    getLeaderId() {
      if (this.memberInfo.deptId) {
        this.deptHeadName = this.columns.filter(
          item => item.DeptId == this.memberInfo.deptId
        )[0].DeptHeadId
        console.log(this.deptHeadName)
        // 如果当前选中的部门已有负责人
        if (this.deptHeadName) {
          this.leaderId = this.deptHeadName
          console.log(this.leaderId)
          this.roleForm = 0
          this.checked = false
        } else {
          this.roleForm = 1
          this.checked = true
        }
      } else {
        this.deptHeadName = ''
        this.checked = false
      }
    },
    // 点击picker选择器的确认按钮
    onConfirm(value) {
      console.log(value)
      this.deptName = value.DeptName
      this.memberInfo.deptId = value.DeptId
      this.getLeaderId()
      this.showPicker = false
      console.log(this.memberInfo.deptId)
      // 如果选择了部门id
      // if (this.memberInfo.deptId) {
      //   this.deptHead = this.columns.filter(
      //     item => item.DeptId == this.memberInfo.deptId
      //   )[0].DeptHead
      //   console.log(this.deptHead)
      //   if (!this.deptHead) {
      //     this.checked = true
      //     this.roleForm = 1
      //     // this.disabledDeptHead = true
      //   }
      // }
    },
    // 点击提交按钮
    submit(val) {
      console.log('点击提交按钮')
      console.log(this.memberInfo)
      // console.log(params)
      // 如果是添加成员的保存
      if (this.role == 2) {
        if (this.checked) {
          // this.checkedRole = this.id
          this.roleForm = '1'
        } else {
          // this.checkedRole = '0'
          this.roleForm = '0'
        }
      }
      // 如果是添加成员的保存按钮
      if (val == 1) {
        console.log(this.memberInfo.deptId)
        this.$axios({
          url: '/attendance-api/employee-add',
          method: 'POST',
          data: {
            mobile: this.memberInfo.mobile,
            name: this.memberInfo.username,
            leaderId: this.leaderId,
            deptId: this.memberInfo.deptId,
            email: this.memberInfo.email,
            role: this.roleForm,
            vendor: this.memberInfo.vendor,
            work_start: this.memberInfo.work_start,
            work_end: this.memberInfo.work_end
          }
        }).then(res => {
          console.log(res)
          // 提交数据到成员管理页面
          if (res) {
            SuccesFN(res.data.Message)
            if (this.roleForm == 1) {
              this.$axios({
                url: '/attendance-api/department-update',
                method: 'POST',
                data: {
                  deptId: this.memberInfo.deptId,
                  deptName: this.deptName,
                  deptHead: this.memberInfo.username,
                  deptHeadId: res.data.Object
                }
              }).then(res => {
                if (res) {
                  // SuccesFN(res.data.Message)
                }
              })
            }
            this.$router.go(-1)
          }
        })
      } else if (val == 2) {
        console.log(this.leaderId)
        // 如果是添加成员的保存并继续添加
        this.$axios({
          url: '/attendance-api/employee-add',
          method: 'POST',
          data: {
            mobile: this.memberInfo.mobile,
            name: this.memberInfo.username,
            leaderId: this.leaderId,
            deptId: this.memberInfo.deptId,
            email: this.memberInfo.email,
            role: this.roleForm,
            vendor: this.memberInfo.vendor,
            work_start: this.memberInfo.work_start,
            work_end: this.memberInfo.work_end
          }
        }).then(res => {
          console.log(res)
          // 提交数据到成员管理页面
          if (res) {
            SuccesFN(res.data.Message)
            if (this.roleForm == 1) {
              this.$axios({
                url: '/attendance-api/department-update',
                method: 'POST',
                data: {
                  deptId: this.memberInfo.deptId,
                  deptName: this.deptName,
                  deptHead: this.memberInfo.username,
                  deptHeadId: res.data.Object
                }
              }).then(res => {
                if (res) {
                  this.memberInfo.username = ''
                  this.memberInfo.mobile = ''
                  this.memberInfo.email = ''
                  this.memberInfo.vendor = ''
                  // this.memberInfo.work_start = ''
                  // this.memberInfo.work_end = ''
                  // this.memberInfo.deptId = ''
                  // this.deptName = ''
                  this.checked = false
                  this.roleForm = 0
                  // this.leaderId = ''
                }
              })
            } else {
              this.memberInfo.username = ''
              this.memberInfo.mobile = ''
              this.memberInfo.email = ''
              this.memberInfo.vendor = ''
              // this.memberInfo.work_start = ''
              // this.memberInfo.work_end = ''
              // this.memberInfo.deptId = ''
              // this.deptName = ''
              this.checked = false
              this.roleForm = 0
              // this.leaderId = ''
            }
          }
        })
      } else if (val == 3) {
        // 如果是编辑成员的保存
        console.log(this.paramsInfo.Id)
        this.$axios({
          url: '/attendance-api/employee-update',
          method: 'POST',
          data: {
            id: this.paramsInfo.Id,
            name: this.memberInfo.username,
            email: this.memberInfo.email,
            mobile: this.memberInfo.mobile,
            role: this.roleForm,
            deptId: this.memberInfo.deptId,
            leaderId: this.leaderId,
            vendor: this.memberInfo.vendor,
            work_start: this.memberInfo.work_start,
            work_end: this.memberInfo.work_end
          }
        }).then(res => {
          console.log(res)
          if (res) {
            SuccesFN(res.data.Message)
            if (this.roleForm == 1) {
              this.$axios({
                url: '/attendance-api/department-update',
                method: 'POST',
                data: {
                  deptId: this.memberInfo.deptId,
                  deptName: this.deptName,
                  deptHead: this.memberInfo.username,
                  deptHeadId: this.paramsInfo.Id
                }
              }).then(res => {
                if (res) {
                  // SuccesFN(res.data.Message)
                }
              })
            }
            this.$router.go(-1)
          }
        })
      } else if (val == 4) {
        // 如果是编辑成员的删除
        this.$axios({
          url: '/attendance-api/employee-delete',
          method: 'DELETE',
          params: {
            id: this.paramsInfo.Id,
            mobile: this.paramsInfo.Mobile
          }
        }).then(res => {
          if (res) {
            SuccesFN(res.data.Message)
            this.$router.go(-1)
          }
        })
      }
    },
    // 点击返回按钮
    goBackHandle() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.addMember:deep {
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;
  .van-nav-bar__arrow {
    font-size: 18px;
    color: #000;
  }
  .van-nav-bar__content {
    .van-nav-bar__title {
      font-size: 18px;
    }
  }
  .dataContent {
    .contentTop {
      padding-top: 10px;
      background-color: #f5f5f5;
    }
    .contentTop:first-child {
      margin-top: 56px;
      background-color: #f5f5f5;
    }
  }
  .van-icon {
    padding-top: 3px;
  }
  .footer {
    position: fixed;
    bottom: 0;
    display: flex;
    width: 100%;
    .van-button {
      flex: 1;
      margin: 10px 16px;
      background: #e3efff;
      color: #006dff;
      font-size: 16px;
      border-radius: 10px;
      border: 0;
    }
    .van-button:last-child {
      margin-left: 0;
      background-color: #006dff;
      color: #fff;
    }
  }
}
</style>
